--
-- Author: shineflag
-- Date: 2016-09-23 10:42:53
--

local skynet = require "skynet"
local service = require "service"
local client = require "client"
local log = require "log"
local proto = require("proto_json")

local TAG = "AGENT"

local agent = {}
local data = {}
local command = {}  --客户端发过来的命令字

function command.ping(cli,args)
	--assert(cli.login)
	log.d(TAG,"userid[%s] ping",cli.userid )

	local resp = args
	local pkg = proto.create_resp("ping",resp)
	return pkg 
end

function command.login(cli,args)

	local ret = 0
	if data.fd then
		log.d(TAG,"login fail %s fd=%d", data.userid, cli.fd)
		ret = 1
	else
		data.fd = cli.fd
		cli.login = true
		log.d(TAG,"login succ %s fd=%d", data.userid, cli.fd)
		local pkg = proto.create_resp("ping",{t=0})
		client.send_pkg(cli.fd,pkg)
	end

	return proto.create_resp("login",{ret=ret})
end

function command.alloc( cli, args )

end

function command.guest_bet( cli, args )
	if not cli.room_addr then
		return proto.create_resp("guess_bet",{ret=1})
	else
		local info = skynet.call(cli.room_addr,"lua","guest_bet",cli.userid,args)
		return proto.create_resp("guess_bet",info)
	end
end


local function ondata(cli,data)
	local info = proto.unpack(data)
	if info.cmd then
		local f = command[info.cmd] 
		if f then
			return f(cli,info.req)
		else
			log.e(TAg,"not proc to cmd[%s]",cmd)
		end
	else
		log.e(TAG,"not cmd data:",data)
	end

	return nil 
end

local function new_user(fd)
	local cli = { name = "agent" .. data.userid,fd = fd }
	cli.userid = data.userid
	cli.ondata = ondata
	local ok, error = pcall(client.dispatch , cli)
	log.d(TAG,"fd=%d is gone. error = %s", fd, error)
	client.close(fd)
	if data.fd == fd then
		data.fd = nil
		skynet.sleep(1000)	-- exit after 10s
		if data.fd == nil then
			-- double check
			if not data.exit then
				data.exit = true	-- mark exit
				skynet.call(service.manager, "lua", "exit", data.userid)	-- report exit
				log.d(TAG,"user %s afk", data.userid)
				skynet.exit()
			end
		end
	end
end


function agent.assign(fd, userid)
	if data.exit then
		return false
	end
	if data.userid == nil then
		data.userid = userid
	else
		log.e(TAG,"reconnected old[%s] now[%s]",data.userid, userid)
	end
	TAG = "AGENT_" .. userid 
	assert(data.userid == userid)
	skynet.fork(new_user, fd)
	return true
end


local mod = service.create_service_model()
mod.command = agent
mod.info = data
mod.reqsrv = {
		"manager",
	}
service.init(mod)
